<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 消息提示区 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center class="alertinfo"> </el-alert>

      <!-- 步骤条区域 -->
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsForm" label-width="100px" label-position="top">
        <!-- 左侧的tabs区域 -->
        <el-tabs tab-position="left" v-model="active" :before-leave="TabChange">
          <el-tab-pane label="基本信息" name="0">
            <!-- 表单面板区域 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器商品分类 -->
              <el-cascader v-model="addGoodsForm.goods_cat" :options="goodsCateCascader" :props="casProps" clearable @change="limitSel"></el-cascader
            ></el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框组 -->
            <el-form-item v-for="item in paramsList" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(val, index) in item.attr_vals" :key="index" :label="val" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in attrList" :key="item.attr_id" :label="item.attr_name">
              <!-- 该input的的值被绑在attrList数组内 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item>
              <!-- on-preview预览图片是触发 -->
              <!-- action表示图片上传的地址 -->
              <!-- file-list是文件列表不需要 -->
              <!-- list-type表示是这么展示图片的 -->
              <el-upload :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove" :headers="uploadHeader" list-type="picture" :on-success="uploadSuccess">
                <el-button size="small" type="primary">上传图片</el-button>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addGoodsForm.goods_introduce" @change="onEditorChange($event)" class="editor" />
            <!-- 添加商品的按钮 -->
            <el-row :gutter="20" class="addBtn">
              <el-col :span="24"><el-button type="primary" @click="addGoods">添加商品</el-button></el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片展示的对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制步骤条的激活
      active: '0',
      // 添加商品表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        attrs: [],
        pics: [],
        // 商品描述
        goods_introduce: ''
      },
      // 添加商品表单的验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '价格不能为空' },
          { type: 'number', message: '价格必须为数字值' }
        ],
        goods_weight: [
          { required: true, message: '重量不能为空' },
          { type: 'number', message: '重量必须为数字值' }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空' },
          { type: 'number', message: '商品数量必须为数字值' }
        ],
        goods_cat: [{ required: true, message: '商品分类不能为空' }]
      },
      // 商品分类级联选择器的值
      goodsCateCascader: [],
      // 商品分类级联选择器配置对象
      casProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },

      // 发起参数请求的参数
      attr_sel: 'many',
      // 参数列表
      paramsList: [],
      // 属性列表
      attrList: [],
      // 上传图片的url地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片的请求头
      uploadHeader: {
        Authorization: sessionStorage.getItem('token')
      },
      // 预览图片的url
      previewUrl: '',
      // 预览图片的对话框
      previewDialogVisible: false
    }
  },
  methods: {
    // 获取商品分类的数据
    async getGoodsCate() {
      const res = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 将值赋值给goodsCateCascader
      this.goodsCateCascader = res.data
    },

    // 使得商品分类级联选择器只能选中三级选择器,并且或取动态参数列表
    limitSel(val) {
      if (val.length !== 3) {
        this.addGoodsForm.goods_cat = []
        return this.$message.warning('只能选中三级分类')
      }
    },
    // 限制页签的跳转
    TabChange(newdata, olddata) {
      // 判断是获取动态参数还是静态属性
      if (newdata === '1') {
        this.attr_sel = 'many'
        this.getGoodsParams()
      } else if (newdata === '2') {
        this.attr_sel = 'only'
        this.getGoodsParams()
      }
      if (olddata === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.warning('必须先选择三级分类')
        return false
      }
      return true
    },
    // 发起获取参数的axios
    async getGoodsParams() {
      // 发起ajax请求
      const res = await this.$http.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`, {
        params: {
          sel: this.attr_sel
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }

      if (this.active === '1') {
        res.data.forEach(val => {
          val.attr_vals = val.attr_vals ? val.attr_vals.split(' ') : []
        })
        this.paramsList = res.data
      } else if (this.active === '2') {
        this.attrList = res.data
      }
    },
    // 测试用的
    cs() {
      console.log(this.paramsValue)
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 处理图片移除图片的操作
    handleRemove(file) {
      const index = this.addGoodsForm.pics.findIndex(val => val.pic === file.response.data.tmp_path)
      // 删除对应的pic
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功时的钩子
    uploadSuccess(res) {
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      const picInfo = {
        pic: res.data.tmp_path
      }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 检测富文本编辑器的改变
    onEditorChange() {
      console.log(1)
    },
    // 实现添加按钮
    addGoods() {
      this.$refs.addGoodsForm.validate(async valid => {
        if (!valid) {
          this.active = '0'
          return this.$message.error('表单验证失败')
        }
        // 对商品分类镜像字符串转换
        this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
        // 对atrs进行处理
        if (this.paramsList !== []) {
          // 将参数列表的属性值进行修改
          this.paramsList.forEach(item => {
            item.attr_vals = item.attr_vals.join(' ')
          })
          this.addGoodsForm.attrs.push(...this.paramsList)
        }
        if (this.attrList !== []) {
          this.addGoodsForm.attrs.push(...this.attrList)
        }

        // 数据处理完毕axios请求添加商品
        const res = await this.$http.post('goods', this.addGoodsForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.active = '6'
        this.$refs.addGoodsForm.resetFields()
      })
    }
  },
  mounted() {
    this.getGoodsCate()
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-cascader {
  width: 250px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-dialog {
  img {
    width: 100%;
  }
}
.addBtn {
  margin-top: 15px;
}
</style>
